﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using Lrd.Template.Core.Infrastructure.Extensions;

namespace Lrd.Template.Core.Infrastructure.Dependency
{


    /// <summary>
    /// Ioc管理
    /// </summary>
    public sealed class IocManage
    {
        private IServiceProvider _provider;

        private IServiceCollection _services;

        /// <summary>
        /// Ioc管理实例
        /// </summary>
        private static readonly Lazy<IocManage> InstanceLazy = new Lazy<IocManage>(() => new IocManage());
        private IocManage()
        {

        }



        public static IocManage Instance => InstanceLazy.Value;


        /// <summary>
        /// 设置应用程序服务提供者
        /// </summary>
        internal void SetApplicationServiceProvider(IServiceProvider provider)
        {
            provider.NotNull(nameof(provider));
           _provider = provider;

        }

        internal void SetServiceCollection(IServiceCollection services) {

            services.NotNull(nameof(services));
            _services = services;
        }


        /// <summary>
        /// 获取 <see cref="ServiceLifetime.Scoped"/>生命周期的服务提供者
        /// </summary>
        public IServiceProvider ScopedProvider
        {
            get
            {
                IScopedServiceResolver scopedResolver = _provider.GetService<IScopedServiceResolver>();
                return scopedResolver != null && scopedResolver.ResolveEnabled
                    ? scopedResolver.ScopedProvider
                    : null;
            }
        }






        /// <summary>
        /// 得到服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>

        public T GetService<T>()
        {


            IScopedServiceResolver scopedResolver = _provider.GetService<IScopedServiceResolver>();
            if (scopedResolver != null && scopedResolver.ResolveEnabled)
            {
                return scopedResolver.GetService<T>();
            }
            return _provider.GetService<T>();
        }


        /// <summary>
        /// 获取当前是否处于<see cref="ServiceLifetime.Scoped"/>生命周期中
        /// </summary>
        /// <returns></returns>ss
        public static bool InScoped()
        {
            return Instance.ScopedProvider != null;
        }

        /// <summary>
        /// 得到日志记录
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public ILogger GetLogger<T>()
        {
            ILoggerFactory factory = _provider.GetService<ILoggerFactory>();
             return factory.CreateLogger<T>();
        }

    }
}
